﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace Twi.COMMON.WPF
{
    public class ValidationManager
    {
        private List<Tuple<UIElement, DependencyProperty, object, string, ValidationType>> _validationItemList = new List<Tuple<UIElement, DependencyProperty, object, string, ValidationType>>();

        public void AddTextBoxRequired(TextBox ctrl, string errMsg) 
        {
            _validationItemList.Add(new Tuple<UIElement,DependencyProperty,object,string,ValidationType>(ctrl, TextBox.TextProperty, "", errMsg, ValidationType.Required)); 
        }

        public void AddRequired(UIElement ctrl, DependencyProperty prop, object emptyValue, string errMsg) 
        {
            _validationItemList.Add(new Tuple<UIElement, DependencyProperty, object, string, ValidationType>(ctrl, prop, emptyValue, errMsg, ValidationType.Required)); 
        }
        
        private bool ValidateRequired(UIElement ctrl, DependencyProperty prop, object emptyValue) 
        {
            if (string.Format("{0}", ctrl.GetValue(prop)).Trim() == emptyValue.ToString()) //属性值有可能是NULL，所以用string.Format
            {
                return false;
            }
            return true;
        }

        public bool Validate() 
        {
            foreach (var i in _validationItemList) 
            {
                if (i.Item5 == ValidationType.Required)
                {
                    if (!ValidateRequired(i.Item1, i.Item2, i.Item3))
                    {                        
                        Tools.GMessageInfo(i.Item4);
                        if (i.Item1 is DialogInputBox)
                        {
                            (i.Item1 as DialogInputBox).OpenDialogBox();
                        }
                        else
                        {
                            i.Item1.Focus();
                        }
                        return false;
                    }
                }
                else if(i.Item5 == ValidationType.Alert)
                {   

                }
            }
            return true;
        }

    }

   public enum ValidationType 
   {
       Required = 1, Alert
   };

}
